//
//  ZYSportTracking.m
//  LoveSport
//
//  Created by 王朝阳 on 2016/11/8.
//  Copyright © 2016年 wangzhaoyang. All rights reserved.
//

#import "ZYSportTracking.h"

@implementation ZYSportTracking {
    //记录起点位置
    CLLocation *_startLocation;
    //运动轨迹模型数组
    NSMutableArray <ZYSportTrackingLine *>*_trackingLines;
}
- (instancetype)initWithType:(ZYSportType)type state:(ZYSportState)state {
    if (self = [super init]) {
        _sportType = type;
        _sportState = state;
        _trackingLines = [NSMutableArray array];
    }
    return self;
}

- (CLLocation *)sportStartLocation {
    return _trackingLines.firstObject.startLocation;
}
- (UIImage *) sportImage {
    UIImage *image;
    switch (_sportType) {
        case ZYSportRun:
            image = [UIImage imageNamed:@"map_annotation_run"];
            break;
        case ZYSportWalk:
            image = [UIImage imageNamed:@"map_annotation_walk"];
            break;
        case ZYSportBike:
            image = [UIImage imageNamed:@"map_annotation_bike"];
            break;
    }
    return image;
}
#pragma mark - 重写 set 方法
- (void)setSportState:(ZYSportState)sportState {
    _sportState = sportState;
    //判断运动状态,如果不是继续,清空起始点
    if (_sportState != ZYSportStateContinue) {
        _startLocation = nil;
    }
}
- (ZYSportPolyline *)appendLocation:(CLLocation *)location {
    // 1.
  
//    //2.判断速度是否发生变化 - 性能优化
    if (location.speed <= 0) {
        
        return nil;
    }
    //将定位时间和当前时间作比较,如果差值过大,说明信号不太好
    //目的是为了性能优化,减少不必要的数据点,减少杂线
    CGFloat factor = 2;
    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] > factor) {
        //如果超过时间差值,就认为定位不够
        return nil;
    }
    //判断起点是否存在
    if (_startLocation == nil) {
        _startLocation = location;
        return nil;
    }
    //3.创建追踪模型
    ZYSportTrackingLine *trackingLine = [[ZYSportTrackingLine alloc] initWithStartLocation:_startLocation endLocation:location];
    [_trackingLines addObject:trackingLine];
    
    NSLog(@"%f-%f-%f-%f", self.avgSpeed, self.maxSpeed, self.totalTime, self.totalDistance);
    //4.让终点成为下一个起点
    _startLocation = location;
    //5.返回折线模型
    return trackingLine.polyline;
}

- (double)avgSpeed {
    return [[_trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}

- (double)maxSpeed {
    return [[_trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
}

- (double)totalTime {
    return [[_trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}

- (double)totalDistance {
    return [[_trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
}







@end
